package config

import (
	"os/exec"
	"os"
	"path"
	"io/ioutil"
	"log"
	"encoding/json"
)

type Cfg struct {
	ConfigFilePath string
	Debug          bool                `json:"debug"`
	Listener       string              `json:"listener"`
	RedisServer    string              `json:"redis_server"`
	RedisPassword  string              `json:"redis_password"`
	RedisDatabase  string              `json:"redis_database"`
	DingWebHook    string              `json:"ding_web_hook"`
	AppMap         map[string]string   `json:"app_map"`
	RelationMap    map[string][]string `json:"relation_map"`
}

const (
	configFileName = "config.json"
	MaxTopicCount  = 100000 //单个topic允许最大堆积数据量
)

var (
	WorkDir       string                  //运行时项目的当前目录（编译后的二进制文件所在的目录）
	Debug         bool                    //debug模式（日志打印到标准输出）
	Listener      string                  //服务监听地址
	RedisServer   string                  //Redis地址
	RedisPassword string                  //Redis密码
	RedisDatabase string                  //Redis数据库
	DingWebHook   string                  //钉钉机器人web hook
	AppMap        map[string]string       //授权app_id和app_secret的映射对
	RelationMap   = map[string][]string{} //订阅关系映射
)

func init() {
	file, _ := exec.LookPath(os.Args[0])
	WorkDir = path.Dir(file)
	NewCfg(path.Join(WorkDir, configFileName)).parse()
}

func NewCfg(file string) (c *Cfg) {
	return &Cfg{
		ConfigFilePath: file,
		AppMap:         make(map[string]string),
	}
}

func (c *Cfg) parse() {
	data, err := ioutil.ReadFile(c.ConfigFilePath)
	if err != nil {
		log.Fatalln("Loading config file error: " + err.Error())
	}
	if err := json.Unmarshal(data, c); err != nil {
		log.Fatalf("Parse config fail, json unmarshal error: %s.", err)
	}

	Debug = c.Debug
	Listener = c.Listener
	RedisServer = c.RedisServer
	RedisPassword = c.RedisPassword
	RedisDatabase = c.RedisDatabase
	DingWebHook = c.DingWebHook
	AppMap = c.AppMap
	RelationMap = c.RelationMap
}
